import {
  audience_info,
  broadcast_info,
  change_recording_layout,
  endBroadcast,
  endRecording,
  startBroadcast,
  startRecording,
} from '@/services/broadcast';
import age from '@/utils/age';
import { random_int } from '@/utils/randomstring';
import { SearchOutlined } from '@ant-design/icons';
import AgoraRTC from 'agora-rtc-sdk-ng';
import AgoraRTM from 'agora-rtm-sdk';
import { Button, Input, message, Modal, Select } from 'antd';
import Countdown from 'antd/es/statistic/Countdown';
import moment from 'moment';
import { useEffect, useState } from 'react';
import './index.less';

var RTCclient: any;
var RTMclient: any;
var RTMchannel: any;
// 用来放置本地音视频频轨道对象
var localAudioTrack: any;
var localVideoTrack: any;
// 屏幕共享音频视频轨道对象
var ScreenAudioTrack = null;
var ScreenVideoTrack: any = null;
// 录制随机uid
var record_uuid = random_int(7).toString();
// 频道名称
var channel = '';
// 开始录制时返回的资源id
var sid = '';
var resourceId = '';
//录制开始时间
var start_time = '';
// 观众列表
var list: any[] = [];

const options = {
  appId: '268a993cd77249cf9f3c1e09a279e96c',
};
const videoConfig: any = {
  // 预设分辨率 默认 480p_1 1080p_1 720p_1
  encoderConfig: '720p_1',
  // cameraId: '03928361c083ae0b6b59ec5af23614eb55febd916a122e749add59c2ab143bfa',
};
const Broadcast_index = (props: any) => {
  // 获取URL参数
  const getUrlParam = (name: string) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return decodeURIComponent(r[2]);
    }
    return null;
  };
  // 存储当前直播id
  const broadcastId: any = getUrlParam('id');
  // console.log('id', broadcastId);
  // 存储直播详情
  const [broadcastinfo, setbroadcastinfo] = useState<any>(undefined);
  // 摄像头列表
  const [camera, setCamera] = useState<any>([]);
  // 存储在线观看人数
  const [total_num, settotal_num] = useState(0);
  // 存储观众列表
  const [audienceList, setAudienceList] = useState<any>([]);
  // 模糊查询观众列表
  const [searchList, setSearchList] = useState<any>([]);
  // 存储互动人员列表
  const [actionList, setActionList] = useState<any>([]);
  // 开始/结束录制按钮loading状态
  const [startloading, setstartloading] = useState(false);
  // 控制显示开始录制还是结束录制
  const [recordstatus, setRecordstatus] = useState(false);
  // 控制开始录制按钮
  const [startVisbble, setstartVisbble] = useState(false);
  // 控制结束录制按钮
  const [endVisbble, setendVisbble] = useState(false);
  // 控制摄像头的关闭与开启状态
  const [videostatus, setVideostatus] = useState(true);
  // 控制摄像头高亮状态
  const [videoColor, setVideoColor] = useState(false);
  // 控制麦克风的关闭与开启状态
  const [audiostatus, setAudiostatus] = useState(true);
  // 控制麦克风高亮状态
  const [audioColor, setAudioColor] = useState(false);
  // 控制屏幕分享与停止分享的状态
  const [sharestatus, setSharestatus] = useState(true);
  // 控制屏幕分享高亮状态
  const [shareColor, setShareColor] = useState(false);
  // 控制观众信息标签展示与隐藏的状态
  const [infoVisibble, setInfoVisible] = useState(false);
  // 存储当前观众的详情
  const [infodata, setInfodata] = useState<any>(null);
  // 控制结束直播弹窗状态
  const [closeVisibble, setCloseVisibble] = useState(false);
  // 控制加入互动观众的模态框状态
  const [addActionModal, setAddactionModal] = useState(false);
  // 控制移除互动观众的模态框状态
  const [delActionModal, setDelactionModal] = useState(false);
  // 存储当前观众的信息
  const [audienceItem, setAudienceItem] = useState<any>({});
  // 存储当前互动观众的index
  const [actionIndex, setActionIndex] = useState<number>();
  // 存储聊天列表
  const [chatList, setChatList] = useState([]);
  // 存储互动人员推流人数
  const [actionNum, setActionNum] = useState(0);
  // 存储互动人员推流人数
  const [userPushList, setUserPushList] = useState<any>([]);
  // 输入框内容
  const [audienceName, setAudienceName] = useState('');

  // 监听页面刷新或关闭
  useEffect(() => {
    window.addEventListener('beforeunload', reload);
    return () => {
      window.removeEventListener('beforeunload', reload);
      reload();
    };
  }, []);
  const reload = () => {
    //页面刷新/退出处理
    end_recording();
  };

  // 页面初始化
  useEffect(() => {
    const fetchData = async () => {
      // 获取聊天记录
      setChatList(JSON.parse(localStorage.getItem('chatList') || '[]'));
      // 自动录制弹窗提示
      info();
      // 获取摄像头列表
      getCameras();
      // 获取直播信息
      get_broadcast_info();
      // 开始直播
      start_broadcast();
      // 从localStorage中获取互动人员列表数据
      const storedActionList = JSON.parse(localStorage.getItem('actionList') || '[]');
      setActionList(storedActionList);
    };
    fetchData();
  }, []);
  // 监听互动人员推流人数
  useEffect(() => {
    console.log('监听互动人员推流人数', userPushList.length);
    if (userPushList.length > 0) {
      changeRecordingLayout(2)
    } else {
      changeRecordingLayout(0)
    }
  }, [userPushList])

  // 修改录制布局
  const changeRecordingLayout = async (layoutType: number) => {
    let request_body = {
      cname: channel,
      uid: record_uuid,
      resourceId,
      sid,
      mixedVideoLayout: layoutType
    }
    let res: any = await change_recording_layout(request_body)
    console.log('修改录制布局', res);
  }

  // 获取直播信息
  const get_broadcast_info = async () => {
    let request_body = {
      id: broadcastId,
    };
    let res: any = await broadcast_info(request_body);
    console.log('直播详情', res);
    if (res.msg == 'ok') {
      setbroadcastinfo(res.data);
    }
  };
  // 获取摄像头列表
  const getCameras = async () => {
    var cameras = await AgoraRTC.getCameras();
    console.log('cameras', cameras);
    let newCamera: any = [];
    cameras.map((item: any) => {
      let temp: any = {};
      temp.value = item.deviceId;
      temp.label = item.label;
      newCamera.push(temp);
    });
    setCamera(newCamera);
  };
  // 开始直播
  const start_broadcast = async () => {
    // 获取uuid channel rtcToken rtmToken
    if (broadcastId) {
      console.log(broadcastId);
      let request_body = {
        id: Number(broadcastId),
      };
      let res: any = await startBroadcast(request_body);
      console.log('uuid', res);
      if (res.msg == 'ok') {
        channel = res.data.channel;
        RTCclient = AgoraRTC.createClient({ mode: 'live', codec: 'vp8' });
        RTCclient.setClientRole('host');
        RTCclient.on('user-published', async (user: any, mediaType: any) => {
  
          setUserPushList((userPushList: any) => {
            console.log('userPushList.includes(user.uid)',userPushList.includes(user.uid));
            if (!userPushList.includes(user.uid)) {
              return [...userPushList, user.uid]
            }
            else{
              return userPushList;
            }
          });
          await RTCclient.subscribe(user, mediaType);
          console.log('user-published', user, mediaType);
          if (mediaType == 'video') {
            console.log('有用户推视频流了');

            setActionList((actionList: any) => {
              let newList = actionList;
              newList.map((item: { uuid: number; actionUpStatus: boolean }) => {
                if (item.uuid == user.uid) {
                  item.actionUpStatus = false;
                }
              });
              localStorage.setItem('actionList', JSON.stringify([...newList]));
              return [...newList];
            });
            // 订阅完成后，从 `user` 中获取远端视频轨道对象
            const remoteVideoTrack = user.videoTrack;
            // 动态插入一个 DIV 节点作为播放远端视频轨道的容器
            // playerContainer = document.getElementById('audience');
            // 订阅完成，播放远端音视频
            // 传入 DIV 节点，让 SDK 在这个节点下创建相应的播放器播放远端视频
            remoteVideoTrack.play(document.getElementById('audience'), {
              mirror: false,
              fit: 'contain',
            });
          }
          if (mediaType == 'audio') {
            // 订阅完成后，从 `user` 中获取远端音频轨道对象
            const remoteAudioTrack = user.audioTrack;
            // 播放音频因为不会有画面，不需要提供 DOM 元素的信息
            remoteAudioTrack.play();
          }
        });
        RTCclient.on('user-unpublished', async (user: any, mediaType: any) => {
          console.log('user-unpublished', user, mediaType);

          setUserPushList((userPushList: any) => {
            return userPushList.filter((el: any) => el !== user.uid);
          });

          setActionList((actionList: any) => {
            let newList = actionList;
            newList.map((item: { uuid: number; actionUpStatus: boolean }) => {
              if (item.uuid == user.uid) {
                item.actionUpStatus = true;
              }
            });
            localStorage.setItem('actionList', JSON.stringify([...newList]));
            return [...newList];
          });
          // 远端用户取消发布或离开频道
          if (mediaType === 'video') {
            // 获取刚刚动态创建的 DIV 节点
            const playerContainer: any = document.getElementById('audience');
            // 销毁这个节点

            // playerContainer.innerHTML = '';
          }
        });
        RTCclient.join(options.appId, res.data.channel, res.data.rtctoken, res.data.uuid).then(
          async () => {
            // 开始录制
            start_recording(res.data.channel);
            // playerContainer = document.getElementById('host');
            localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
            localVideoTrack = await AgoraRTC.createCameraVideoTrack(videoConfig);
            await RTCclient.publish([localAudioTrack, localVideoTrack]);
            localVideoTrack.play(document.getElementById('host'), {
              mirror: false,
              fit: 'contain',
            });
          },
        );
        // 加入频道
        join(res.data.uuid, res.data.rtmtoken, res.data.channel);
      } else {
        message.error(res.msg);
      }
    }
  };
  // 开始录制按钮回调
  const start_recording = async (channel: string) => {
    console.log('推流人数', userPushList.length);
    // //按钮禁止点击
    setstartloading(true);
    let request_body = {
      id: broadcastId,
      cname: channel,
      uid: record_uuid,
      type: 0,
      fileNamePrefix: process.env.UMI_ENV,
      mixedVideoLayout:userPushList.length > 0?2:0,
    };
    let params: any = await startRecording(request_body);
    console.log('开始录制', params);
    if (params.msg == 'ok') {
      message.success('已开始录制');
      sid = params.data.sid;
      resourceId = params.data.resourceId;
      setRecordstatus(true);
      start_time = moment().format('YYYY-MM-DD HH:mm:ss');
    }
    //按钮可以点击
    setstartloading(false);
  };
  // 结束录制按钮回调
  const end_recording = async () => {
    //按钮禁止点击
    setstartloading(true);
    let request_body = {
      cname: channel,
      uid: record_uuid,
      resourceId,
      sid,
      object_id: broadcastId,
      start_time,
      end_time: moment().format('YYYY-MM-DD HH:mm:ss'),
    };
    let params: any = await endRecording(request_body);
    console.log('结束录制', params);
    if (params.msg == 'ok') {
      message.success('已结束录制');
      setRecordstatus(false);
    }
    //按钮可以点击
    setstartloading(false);
  };
  // 自动录制温馨提示窗
  const info = () => {
    Modal.info({
      title: '温馨提示',
      content: (
        <div>
          <p>平台将自动录制授课视频，您可以手动结束录制，请知悉。</p>
        </div>
      ),
      onOk() { },
    });
  };
  // 结束直播
  const end_broadcast = async () => {
    // 发送频道消息
    RTMchannel.sendMessage({ text: JSON.stringify({ type: 'broadcast_end_%fJ9DG#L' }) });
    // 退出RTM频道
    RTMclient.logout();
    // 停止发布（离开频道会自动停止发布）
    if (RTCclient) {
      await RTCclient.unpublish();
      // 退出直播间。
      await RTCclient.leave();
      RTCclient = null;
    }
    // 销毁本地音视频轨道。
    if (localAudioTrack) {
      localAudioTrack.close();
    }
    if (localVideoTrack) {
      localVideoTrack.close();
    }
    // 结束直播
    let res: any = await endBroadcast({ id: broadcastId });
    console.log('结束直播', res);
    if (res.msg == 'ok') {
      // 直播结束清空互动观众列表
      localStorage.removeItem('actionList');
      localStorage.removeItem('chatList');
      setCloseVisibble(false);
      message.success('直播已结束!');
      setTimeout(() => {
        window.close();
      }, 2000);
    }
  };
  //切换摄像头设备
  const handleCameraChange = async (value: any, label: any) => {
    // 在这里根据value的值切换使用的摄像设备，并更新界面上的直播画面
    videoConfig.cameraId = value;
    const playerContainer: any = document.getElementById('host');
    // 先停止推流
    await RTCclient.unpublish();
    // 清空
    playerContainer.innerHTML = '';
    ScreenVideoTrack = null;
    localAudioTrack = null;
    // 重新开始推流
    localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
    localVideoTrack = await AgoraRTC.createCameraVideoTrack(videoConfig);
    await RTCclient.publish([localAudioTrack, localVideoTrack]);
    localVideoTrack.play(document.getElementById('host'), {
      mirror: false,
      fit: 'contain',
    });
  };

  // 关闭摄像头或开启摄像头
  const change_Videostatus = async (value: any) => {
    setVideostatus(value);
    // 暂时关闭摄像头采集
    await localVideoTrack?.setEnabled(value);
  };

  // 关闭麦克风或开启麦克风
  const change_Audiostatus = async (value: any) => {
    setAudiostatus(value);
    await localAudioTrack?.setEnabled(value);
  };
  // 屏幕分享和停止分享
  const change_Sharestatus = async (value: any) => {
    if (value) {
      setSharestatus(value);
      await RTCclient.unpublish();
      const playerContainer: any = document.getElementById('host');
      playerContainer.innerHTML = '';
      ScreenVideoTrack = null;
      localAudioTrack = null;
      // 通过麦克风采集的音频创建本地音频轨道对象
      localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
      // 通过摄像头采集的视频创建本地视频轨道对象
      console.log(videoConfig);
      localVideoTrack = await AgoraRTC.createCameraVideoTrack(videoConfig);
      // 将这些音视频轨道对象发布到频道中
      await RTCclient.publish([localAudioTrack, localVideoTrack]);
      console.log('publish cameraVideo success!');
      // 播放本地视频轨道对象
      if (playerContainer) {
        localVideoTrack.play(playerContainer, { mirror: false, fit: 'contain' });
      }
    } else {
      // setSharestatus(value);
      // console.log(123);
      await AgoraRTC.createScreenVideoTrack(videoConfig, 'auto').then(async (backTrack: any) => {
        // console.log(456);
        setSharestatus(value);
        await RTCclient.unpublish();
        localAudioTrack = null;
        localVideoTrack = null;
        localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
        if (backTrack[1]) {
          ScreenVideoTrack = backTrack[0];
          ScreenAudioTrack = backTrack[1];
          await RTCclient.publish([ScreenVideoTrack, ScreenAudioTrack, localAudioTrack]);
          const playerContainer: any = document.getElementById('host');
          playerContainer.innerHTML = '';
          backTrack[0].play(playerContainer, { mirror: false });
        } else {
          //视频分享
          ScreenVideoTrack = backTrack;
          // 将这些音视频轨道对象发布到频道中
          await RTCclient.publish([ScreenVideoTrack, localAudioTrack]);
          console.log('publish screenVideo success!');
          // 播放本地视频轨道对象
          const playerContainer: any = document.getElementById('host');
          playerContainer.innerHTML = '';
          backTrack.play(playerContainer, { mirror: false });
        }
      });
      ScreenVideoTrack.on('track-ended', async () => {
        console.log('hjksdhfkh');
        setSharestatus(true);
        const playerContainer: any = document.getElementById('host');
        await RTCclient.unpublish();
        playerContainer.innerHTML = '';
        ScreenVideoTrack = null;
        localAudioTrack = null;
        // 通过麦克风采集的音频创建本地音频轨道对象
        localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
        // 通过摄像头采集的视频创建本地视频轨道对象
        console.log(videoConfig);
        localVideoTrack = await AgoraRTC.createCameraVideoTrack(videoConfig);
        // 将这些音视频轨道对象发布到频道中
        await RTCclient.publish([localAudioTrack, localVideoTrack]);
        console.log('publish cameraVideo success!');
        // 播放本地视频轨道对象
        if (playerContainer) {
          localVideoTrack.play(playerContainer, { mirror: false, fit: 'contain' });
        }
      });
    }
  };
  // 加入RTM频道
  const join = async (uuid: number, rtmtoken: string, channel: string) => {
    console.log(uuid, rtmtoken, channel);
    RTMclient = AgoraRTM.createInstance(options.appId);
    console.log('RTMclient', RTMclient);
    await RTMclient.login({ uid: uuid.toString(), token: rtmtoken });
    RTMchannel = RTMclient.createChannel(channel);
    console.log('Rtm', RTMchannel);
    await RTMchannel.join();
    RTMchannel.sendMessage({
      text: JSON.stringify({
        type: 'personChange',
        data: sendActionList(JSON.parse(localStorage.getItem('actionList') || '[]')),
      }),
    });
    // //进入频道后，查询当前频道全部用户，渲染基础的观众列表
    const nowAudiencelist = await RTMchannel.getMembers();
    // 获取初始观众人数
    get_total_num();
    nowAudiencelist.forEach((e: number) => {
      console.log(e != uuid);
      if (e != uuid) {
        joinChannel(e);
      }
    });
    // 监听用户加入频道
    RTMchannel.on('MemberJoined', (memberId: any) => {
      console.log('MemberJoined:' + memberId);
      // 发送当前互动观众信息(点对点消息)
      RTMclient.sendMessageToPeer(
        {
          text: JSON.stringify({
            type: 'personChange',
            data: sendActionList(JSON.parse(localStorage.getItem('actionList') || '[]')),
          }),
        },
        memberId.toString(),
      );
      // 获取当前在线观看人数
      get_total_num();
      joinChannel(memberId);
    });
    // 监听用户离开频道
    RTMchannel.on('MemberLeft', (memberId: any) => {
      console.log('MemberLeft:' + memberId);
      // 获取当前在线观看人数
      get_total_num();
      leaveChannel(memberId);
    });
    // 频道消息
    RTMchannel.on('ChannelMessage', async (message: any, memberId: any) => {
      console.log('messsage: ', message, ', memberId: ', memberId);
      get_message(JSON.parse(message.text), memberId);
    });
    // 点对点消息，用来处理连麦生命周期 ， 接收挂断通知
    RTMclient.on('MessageFromPeer', async (message: any, peerId: any) => {
      console.log(message);
      console.log('message ', message, ' peerId', peerId);
    });
  };
  // 观众列表监听
  useEffect(() => {
    list = [...audienceList];
  }, [audienceList.length]);

  // 用户加入频道
  const joinChannel = async (audienceId: number) => {
    // 获取观众详情信息
    let info: any = await audience_info({ id: audienceId });
    console.log('info', info);
    if (JSON.stringify(info.data) !== '{}') {
      if (!list.some((item: any) => item.uuid == audienceId)) {
        info.data['uuid'] = audienceId;
        info.data['actionStatus'] = 0;
        info.data['actionUpStatus'] = true;
        setAudienceList(() => {
          list.unshift(info.data);
          return [...list] as never[];
        });
      }
      //判断观众是否在互动池里，如果在，则修改对应的在线状态以及连麦状态
      var actionList = JSON.parse(localStorage.getItem('actionList') || '[]');
      if (actionList.some((item: any) => item.uuid == audienceId)) {
        // 修改互动观众在线状态
        changeActionUserStatus(audienceId, 1);
        // 发送当前互动观众信息
        // RTMchannel.sendMessage({
        //   text: sendActionList(JSON.parse(localStorage.getItem('actionList') || '[]')),
        // });
      }
    }
  };

  // 用户离开频道
  const leaveChannel = (audienceId: number) => {
    //判断观众是否在互动池里，如果在，则修改对应的在线状态
    var actionList = JSON.parse(localStorage.getItem('actionList') || '[]');
    if (actionList.some((item: any) => item.uuid == audienceId)) {
      // 修改互动观众在线状态
      changeActionUserStatus(audienceId, 0);
    }
    // 更新观众列表，移除当前观众
    setAudienceList((audienceList: any) => {
      let newList = audienceList.filter((item: any) => item.uuid != audienceId);
      return newList;
    });
  };

  //获取频道在线人数
  const get_total_num = async () => {
    const ChannelMemberCount = await RTMclient.getChannelMemberCount([channel]);
    let num = ChannelMemberCount[channel] - 1;
    settotal_num(num);
  };

  useEffect(() => {
    console.log('audienceList', audienceList);
    console.log('互动观众', actionList);
  }, [audienceList, actionList]);

  // 点击某个观众的回调
  const showInfo = async (uuid: number) => {
    let res: any = await audience_info({ id: uuid });
    console.log('观众详情', res);
    setInfodata(res.data);
    setInfoVisible(true);
  };
  // 添加为互动人员
  const addAction = () => {
    if (actionList.length < 5) {
      audienceItem['actionStatus'] = 1;
      setActionList([...actionList, audienceItem]);
      localStorage.setItem('actionList', JSON.stringify([...actionList, audienceItem]));
      // 发送当前互动观众信息
      RTMchannel.sendMessage({
        text: JSON.stringify({
          type: 'personChange',
          data: sendActionList(JSON.parse(localStorage.getItem('actionList') || '[]')),
        }),
      });
      // 关闭模态框
      setAddactionModal(false);
    } else {
      message.error('互动观众已满员');
    }
  };
  // 移除互动人员
  const delAction = () => {
    setActionList((actionList: any) => {
      let newList = actionList;
      newList.splice(actionIndex, 1);
      localStorage.setItem('actionList', JSON.stringify([...newList]));
      // 发送当前互动观众信息(频道消息)
      RTMchannel.sendMessage({
        text: JSON.stringify({
          type: 'personChange',
          data: sendActionList(JSON.parse(localStorage.getItem('actionList') || '[]')),
        }),
      });
      // 关闭模态框
      setDelactionModal(false);
      return [...newList];
    });
  };
  //修改互动观众在线状态
  const changeActionUserStatus = (memberId: number, status: number) => {
    setActionList((actionList: any) => {
      let newList = actionList;
      newList.map((item: { uuid: number; actionStatus: number }) => {
        if (item.uuid == memberId) {
          item.actionStatus = status;
        }
      });
      localStorage.setItem('actionList', JSON.stringify([...newList]));
      return [...newList];
    });
  };
  // 修改互动观众连麦状态
  const changeActionUserUpStatus = (memberId: number, status: boolean) => {
    setActionList((actionList: any) => {
      let newList = actionList;
      newList.map((item: { uuid: number; actionUpStatus: boolean }) => {
        if (item.uuid == memberId) {
          item.actionUpStatus = status;
        }
      });
      localStorage.setItem('actionList', JSON.stringify([...newList]));
      !status ? actionUserUp(memberId) : actionUserDown(memberId);
      return [...newList];
    });
  };
  // 邀请连麦
  const actionUserUp = (peerId: number) => {
    // 发送点对点消息
    RTMclient.sendMessageToPeer({ text: JSON.stringify({ type: 'shangmai' }) }, peerId.toString());
  };
  // 取消连麦
  const actionUserDown = (peerId: number) => {
    // 发送点对点消息
    RTMclient.sendMessageToPeer({ text: JSON.stringify({ type: 'xiamai' }) }, peerId.toString());
  };

  //接受频道消息
  const get_message = async (message: any, memberId: number) => {
    console.log(message);
    if (message.type === 'message') {
      let info: any = await audience_info({ id: memberId });
      console.log('当前观众详情', info);
      let chat: any = [];
      chat.push({
        head_img: info.data.head_img,
        username: info.data.username,
        text: message.text,
      });
      setChatList((chatList) => {
        localStorage.setItem('chatList', JSON.stringify([...chatList, ...chat]));
        return [...chatList, ...chat] as never[];
      });
    }
  };
  // 始终滚动到最底部
  useEffect(() => {
    updateScroll();
  }, [chatList]);
  const updateScroll = () => {
    var element = document.getElementById('chatList');
    if (element) {
      element.scrollTop = element.scrollHeight;
    }
  };
  // 处理互动观众列表
  const sendActionList = (array: any) => {
    let audience = array;
    let arr: any = [];
    audience.map((item: any) => {
      arr.push({
        // type: 'action',
        uuid: item.uuid,
        head_img: item.head_img,
        username: item.username,
        platform_name: item.platform_name ? item.platform_name : '',
      });
    });
    return arr;
  };

  // 搜索观众
  const searchAudience = (e: any) => {
    setAudienceName(e.target.value);
    console.log(e.target.value, audienceList);
    if (e.target.value !== '') {
      const newList: any = [];
      audienceList.map((item: any) => {
        if (item.username.indexOf(e.target.value) != -1) {
          newList.push(item);
        }
      });
      setSearchList(newList);
    }
  };
  return (
    <>
      <div className="broadcast-index">
        <div className="header">
          {broadcastinfo === undefined ? (
            ''
          ) : (
            <>
              <div className="title">
                {broadcastinfo.name}
                <span style={{ marginLeft: '26px' }}>距离直播计划结束时间还有：</span>
                <Countdown
                  value={broadcastinfo.end_time}
                  format="HH:mm:ss"
                  style={{ width: '200px', display: 'inline-block', lineHeight: '2px' }}
                  valueStyle={{ color: '#5295FF' }}
                ></Countdown>
              </div>
              <div className="name">
                <span>
                  主讲医生：{`${broadcastinfo.user_name}(${broadcastinfo.positional_name})`}
                </span>
                <span className="num">在线观看人数: {total_num}</span>
                <span className="num">
                  视频设备：
                  {camera.length !== 0 ? (
                    <Select
                      style={{ width: 200, height: 30 }}
                      placeholder="请选择摄像设备"
                      allowClear
                      onChange={(value, label: any) => {
                        console.log('value', value);
                        handleCameraChange(value, label);
                      }}
                      defaultValue={camera[0].value}
                      options={camera}
                    ></Select>
                  ) : (
                    ''
                  )}
                </span>
              </div>
            </>
          )}

          <div className="header_btn">
            <Button
              key="recording"
              type="primary"
              ghost
              loading={startloading}
              onClick={() => {
                recordstatus ? setendVisbble(true) : setstartVisbble(true);
              }}
            >
              {recordstatus ? '结束录制' : '开始录制'}
            </Button>
            <Button
              key="leaveLive"
              type="primary"
              onClick={() => {
                recordstatus ? message.warning('请先结束录制') : setCloseVisibble(true);
              }}
            >
              结束直播
            </Button>
          </div>
        </div>
        <div className="content">
          <div className="content_left">
            <div className="title">观众列表</div>
            <Input
              className="input"
              size="small"
              placeholder="请输入观众姓名"
              value={audienceName}
              onChange={(e) => searchAudience(e)}
              prefix={<SearchOutlined style={{ color: '#92929E ' }} />}
            />
            <div className="audience_list">
              {audienceList.length > 0 ? (
                audienceName == '' ? (
                  audienceList?.map((item: any) => (
                    <div className="audience_info" key={item.uuid}>
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'flex-start',
                          width: '240px',
                        }}
                        onClick={() => showInfo(item.uuid)}
                      >
                        <div>
                          <img
                            style={{ width: '30px', height: '30px', borderRadius: '50%' }}
                            src={item.head_img ? item.head_img : '/head_img.svg'}
                            alt={item.username}
                          />
                        </div>
                        <div className="name">{item.username}</div>
                      </div>
                      <div>
                        <Button
                          type="link"
                          disabled={actionList?.some((list: any) => item.uuid == list.uuid)}
                          onClick={() => {
                            setAddactionModal(true);
                            setAudienceItem(item);
                          }}
                        >
                          <img
                            className="add"
                            src={
                              actionList?.some((list: any) => item.uuid == list.uuid)
                                ? '/images/unadd.png'
                                : '/images/add.png'
                            }
                            alt=""
                          />
                        </Button>
                      </div>
                    </div>
                  ))
                ) : (
                  searchList?.map((item: any) => (
                    <div className="audience_info" key={item.uuid}>
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'flex-start',
                          width: '240px',
                        }}
                        onClick={() => showInfo(item.uuid)}
                      >
                        <div>
                          <img
                            style={{ width: '30px', height: '30px', borderRadius: '50%' }}
                            src={item.head_img ? item.head_img : '/head_img.svg'}
                          />
                        </div>
                        <div className="name">{item.username}</div>
                      </div>
                      <div>
                        <Button
                          type="link"
                          disabled={actionList?.some((list: any) => item.uuid == list.uuid)}
                          onClick={() => {
                            setAddactionModal(true);
                            setAudienceItem(item);
                          }}
                        >
                          <img
                            className="add"
                            src={
                              actionList?.some((list: any) => item.uuid == list.uuid)
                                ? '/images/unadd.png'
                                : '/images/add.png'
                            }
                            alt=""
                          />
                        </Button>
                      </div>
                    </div>
                  ))
                )
              ) : (
                <p
                  style={{
                    marginTop: '50px',
                    textAlign: 'center',
                    color: 'rgba(0, 0, 0, 0.5)',
                  }}
                >
                  暂无观众~
                </p>
              )}
            </div>
            {infoVisibble && infodata ? (
              <>
                <div className="info">
                  <p
                    className="close"
                    onClick={() => {
                      setInfoVisible(false);
                      setInfodata(null);
                    }}
                  >
                    X
                  </p>
                  <p className="oldinfo">观众信息</p>
                  <div className="head_img">
                    <img
                      src={infodata.head_img ? infodata.head_img : '/head_img.svg'}
                    // alt={infodata.username}
                    />
                    <p>{infodata.username}</p>
                  </div>
                  <div>
                    <p>
                      <span className="infotitle">性别：</span>
                      {infodata.sex == 1 ? '男' : '女'}
                    </p>
                  </div>
                  <div>
                    <p>
                      <span className="infotitle">年龄：</span>
                      {age(infodata.birth)}
                    </p>
                  </div>
                  <div>
                    <p>
                      <span className="infotitle">详细地址：</span>
                      {infodata.province_name}
                      {infodata.city_name}
                      {infodata.area_name}
                      {infodata.address}
                    </p>
                  </div>
                  {infodata.info ? (
                    <>
                      <div>
                        <p>
                          <span className="infotitle">现病史：</span>
                          {infodata.info.current_illness || '-'}
                        </p>
                      </div>
                      <div>
                        <p>
                          <span className="infotitle">既往史：</span>
                          {infodata.info.before_illness || '-'}
                        </p>
                      </div>
                      <div>
                        <p>
                          <span className="infotitle">康复治疗记录：</span>
                          {infodata.info.recovery_record || '-'}
                        </p>
                      </div>
                      <div>
                        <p>
                          <span className="infotitle">用药情况：</span>
                          {infodata.info.drug_use || '-'}
                        </p>
                      </div>
                    </>
                  ) : (
                    <>
                      <div>
                        <p>
                          <span className="infotitle">学历：</span>
                          {infodata.education_name || '-'}
                        </p>
                      </div>
                      <div>
                        <p>
                          <span className="infotitle">职称：</span>
                          {infodata.positional_name || '-'}
                        </p>
                      </div>
                      <div>
                        <p>
                          <span className="infotitle">所属机构：</span>
                          {infodata.platform_name || '-'}
                        </p>
                      </div>
                      <div>
                        <p>
                          <span className="infotitle">所属科室：</span>
                          {infodata.department_name || '-'}
                        </p>
                      </div>
                    </>
                  )}
                </div>
              </>
            ) : (
              ''
            )}
          </div>
          <div className="content_video">
            <div className="video">
              {userPushList.length > 0 ? (
                <>
                  <div id="host" style={{ height: '100%', flex: 1 }}></div>
                  <div id="audience" style={{ height: '100%', flex: 1 }}></div>
                </>
              ) : (
                <div id="host" style={{ height: '100%', flex: 1 }}></div>
              )}
            </div>
            <div className="video-btn">
              <div
                className="btn"
                onClick={() => {
                  change_Audiostatus(!audiostatus);
                }}
                onMouseEnter={() => setAudioColor(true)}
                onMouseLeave={() => setAudioColor(false)}
              >
                <img
                  src={
                    audiostatus
                      ? !audioColor
                        ? '/icons/audio.png'
                        : '/icons/audio_b.png'
                      : !audioColor
                        ? '/icons/audio_x.png'
                        : '/icons/audio_x_b.png'
                  }
                  alt=""
                />
                <Button
                  type="link"
                  style={{
                    color: !audioColor ? '#17172E' : '#0064ff',
                    fontSize: '14px',
                    padding: 0,
                  }}
                >
                  {audiostatus ? '静音' : '取消静音'}
                </Button>
              </div>
              <div
                className="btn"
                onClick={() => {
                  change_Videostatus(!videostatus);
                }}
                onMouseEnter={() => setVideoColor(true)}
                onMouseLeave={() => setVideoColor(false)}
              >
                <img
                  src={
                    videostatus
                      ? !videoColor
                        ? '/icons/camera.png'
                        : '/icons/camera_b.png'
                      : !videoColor
                        ? '/icons/camera_x.png'
                        : '/icons/camera_x_b.png'
                  }
                  alt=""
                />
                <Button
                  type="link"
                  style={{
                    color: !videoColor ? '#17172E' : '#0064ff',
                    fontSize: '14px',
                    padding: 0,
                  }}
                >
                  {videostatus ? '关闭摄像头' : '开启摄像头'}
                </Button>
              </div>
              <div
                className="btn"
                onClick={() => {
                  change_Sharestatus(!sharestatus);
                }}
                onMouseEnter={() => setShareColor(true)}
                onMouseLeave={() => setShareColor(false)}
              >
                <Button
                  type="link"
                  style={{
                    color: !shareColor ? '#17172E' : '#0064ff',
                    fontSize: '14px',
                    padding: 0,
                  }}
                  disabled={!sharestatus}
                >
                  <img src={!shareColor ? '/icons/share.png' : '/icons/share_b.png'} alt="" />
                </Button>
                <Button
                  type="link"
                  style={{
                    color: !shareColor ? '#17172E' : '#0064ff',
                    fontSize: '14px',
                    padding: 0,
                  }}
                  disabled={!sharestatus}
                >
                  {sharestatus ? '屏幕分享' : '分享中'}
                </Button>
              </div>
            </div>
          </div>
          <div className="content_right">
            <div className="action">
              <div className="title">互动人员</div>
              <div className="action_list">
                {actionList.length > 0 ? (
                  actionList?.map((item: any, index: number) => (
                    <div
                      key={index}
                      style={{
                        display: 'flex',
                        height: '92px',
                        marginBottom: '10px',
                      }}
                    >
                      <div className="avatar">
                        <img
                          style={{ width: '44px', height: '44px', borderRadius: '50%' }}
                          src={item.head_img ? item.head_img : '/head_img.svg'}
                          alt=""
                        />
                      </div>
                      <div
                        style={{
                          display: 'flex',
                          flexDirection: 'column',
                          height: '92px',
                        }}
                      >
                        <div
                          className="info"
                          style={{ display: 'flex', justifyContent: 'space-between' }}
                        >
                          <div className="name">{item.username}</div>
                          <div
                            className="status"
                            style={{ color: item.actionStatus === 0 ? '#BFBFBF' : '#09CF66' }}
                          >
                            {item.actionStatus === 0 ? '• 离线' : '• 在线'}
                          </div>
                        </div>
                        <div className="positional">{item.platform_name}</div>
                        <div className="btn">
                          <Button
                            className="put"
                            size="small"
                            disabled={item.actionStatus === 0}
                            onClick={() =>
                              changeActionUserUpStatus(item.uuid, !item.actionUpStatus)
                            }
                          >
                            {item.actionUpStatus ? '立即连麦' : '关闭连麦'}
                          </Button>
                          <Button
                            className="out"
                            size="small"
                            danger
                            disabled={!item.actionUpStatus}
                            onClick={() => {
                              setDelactionModal(true);
                              setActionIndex(index);
                            }}
                          >
                            移出
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))
                ) : (
                  <p
                    style={{
                      marginTop: '50px',
                      textAlign: 'center',
                      color: 'rgba(0, 0, 0, 0.5)',
                    }}
                  >
                    暂无互动人员~
                  </p>
                )}
              </div>
            </div>
            <div className="chat">
              <div className="title">聊天室</div>
              <ul
                id="chatList"
                style={{
                  height: '400px',
                  overflow: 'scroll',
                  overflowX: 'hidden',
                  scrollBehavior: 'smooth',
                }}
              >
                {chatList.length > 0 ? (
                  chatList.map((item: any, index: number) => (
                    <li key={index}>
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'flex-start',
                          alignItems: 'center',
                          marginTop: '12px',
                        }}
                      >
                        <div>
                          <img
                            style={{
                              width: '30px',
                              height: '30px',
                              borderRadius: '50%',
                              marginRight: '10px',
                            }}
                            src={item.head_img ? item.head_img : '/head_img.svg'}
                            alt=""
                          />
                        </div>
                        <div
                          style={{
                            fontSize: '14px',
                            fontFamily: 'PingFangSC, PingFang SC',
                            fontWeight: 400,
                            color: '#95969F',
                            lineHeight: '20px',
                          }}
                        >
                          {item.username}
                        </div>
                      </div>
                      <div
                        style={{
                          marginTop: '10px',
                          fontSize: '14px',
                          fontFamily: 'PingFangSC, PingFang SC',
                          fontWeight: 400,
                          color: '#17172A',
                          lineHeight: '20px',
                        }}
                      >
                        {item.text}
                      </div>
                    </li>
                  ))
                ) : (
                  <p
                    style={{
                      marginTop: '50px',
                      textAlign: 'center',
                      color: 'rgba(0, 0, 0, 0.5)',
                    }}
                  >
                    还没有聊天内容~
                  </p>
                )}
              </ul>
            </div>
          </div>
        </div>
      </div>
      {/* 录制开始弹窗提示 */}
      <Modal
        title="开始确认"
        open={startVisbble}
        onOk={() => {
          start_recording(channel);
          setstartVisbble(false);
        }}
        onCancel={() => setstartVisbble(false)}
        okText="确定"
        cancelText="取消"
        width={350}
      >
        <p>即将开始录制，确定要开始吗？</p>
      </Modal>
      {/* 录制结束弹窗提示 */}
      <Modal
        title="结束确认"
        open={endVisbble}
        onOk={() => {
          end_recording();
          setendVisbble(false);
        }}
        onCancel={() => setendVisbble(false)}
        okText="确定"
        cancelText="取消"
        width={350}
      >
        <p>即将结束录制，确定要结束吗？</p>
      </Modal>
      {/* 结束直播弹窗提示 */}
      <Modal
        title="结束确认"
        open={closeVisibble}
        onOk={() => end_broadcast()}
        onCancel={() => setCloseVisibble(false)}
        okText="确定"
        cancelText="取消"
        width={350}
      >
        <p>即将结束直播，确定要结束吗？</p>
      </Modal>
      {/* 添加为互动人员的弹窗提示 */}
      <Modal
        title="加入确认"
        open={addActionModal}
        onOk={() => addAction()}
        onCancel={() => setAddactionModal(false)}
        okText="确定"
        cancelText="取消"
        width={350}
      >
        {audienceItem ? <p>确定要将{audienceItem.username}加入互动人员中吗？</p> : ''}
      </Modal>
      {/* 移除互动人员的弹窗提示 */}
      <Modal
        title="移除确认"
        open={delActionModal}
        onOk={() => delAction()}
        onCancel={() => setDelactionModal(false)}
        okText="确定"
        cancelText="取消"
        width={350}
      >
        {audienceItem ? <p>确定要将{audienceItem.username}移出互动人员吗？</p> : ''}
      </Modal>
    </>
  );
};
export default Broadcast_index;
